package algotithm.interview.newcoder.test2;

/**
 * @author zhouyanxiang
 * @Date 2021-03-2021/3/4-21:07
 * @Title 岛屿数量
 */
public class Solution {

    public static void main(String[] args) {
        Solution solution = new Solution();
        int[][] grid = {
                {1,1,1,1,0},
                {1,1,0,0,0},
                {1,1,0,0,0},
                {0,0,0,0,0}
        };
        int solutionGrid = solution.findGrid(grid);
        System.out.println(solutionGrid);
    }

    private int res = 0;
    public int findGrid(int[][] grid) {
        int n = grid.length;
        int m = grid[0].length;
        int res = 0;
        for (int i = 0; i < n; i++) {
            for (int j = 0;j < m; j++) {
                if (grid[i][j] == 1) {
                    res++;
                    dfs(grid,i,j);
                }
            }
        }
        return res;
    }

    public void dfs(int[][] grid,int i ,int j) {
        if (i < 0 || j < 0 || i >= grid.length || j >= grid[0].length) {
            return;
        }
        if (grid[i][j] == 0) {
            return;
        }
        grid[i][j] = 0;
        dfs(grid,i-1,j);
        dfs(grid,i+1,j);
        dfs(grid,i,j-1);
        dfs(grid,i,j+1);
    }

}
